from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QWidget
import sys
from PySide2.QtCharts import QtCharts
from PySide2.QtWidgets import QHBoxLayout
import openpyxl
from PySide2.QtCore import Qt

class MyChartWidget(QWidget):

    def __init__(self):
        super().__init__()
        self.resize(500, 500)
        # 图
        self.chart = QtCharts.QChart()
        # View
        self.view = QtCharts.QChartView(self.chart)
        # Series
        self.series = QtCharts.QPieSeries()

        #打开Excel
        self.wb = openpyxl.load_workbook(
            r'C:\Users\zuozh\Desktop\太原科大Python综合培训\国家数据\就业人员和工资\按行业分城镇单位就业人员.xlsx'
        )
        self.ws = self.wb['年度数据']

        self.__dataInit()

        # 布局
        layout = QHBoxLayout()
        layout.addWidget(self.view)
        self.setLayout(layout)

    def __dataInit(self):
        # self.series.append("A", 30)
        # self.series.append("B", 70)
        # self.series.append("C", 40)
        for i in range(4, 24):
            temp = str(
                self.ws.cell(row=i, column=1).value
                )
            newTemp = temp[:len(temp) - 4]
            self.series.append(
                newTemp,
                float(
                    self.ws.cell(row=i, column=2).value
                )
            )
        self.series.setLabelsPosition(
            QtCharts.QPieSlice.LabelOutside)
        self.series.setLabelsVisible(True)

        sl = self.series.slices()[1]
        sl.setExploded()    # 突出显示
        sl.setBrush(Qt.red)
        # 将数据添加到表中
        self.chart.addSeries(self.series)
        # 设置表的标题
        self.chart.setTitle('饼图示例')
        self.chart.legend().hide()  # 隐藏图例
        self.chart.setAnimationOptions(
            QtCharts.QChart.AllAnimations
        )


if __name__ == "__main__":
    app = QApplication()

    mcw = MyChartWidget()
    mcw.show()

    sys.exit(app.exec_())